package com.example.mybatisplus.dynamic;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    private Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    @Pointcut("@annotation(com.example.mybatisplus.dynamic.DynamicDataSource)")
    public void mapperMethod() {
    }

    @Around("mapperMethod()")
    public Object setDataSource(ProceedingJoinPoint joinPoint) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        DynamicDataSource dynamicDataSource = method.getAnnotation(DynamicDataSource.class);
        String dataSourceKey = dynamicDataSource.value();
        MultipleDataSource.setCurrentLookupKey(dataSourceKey);
        logger.info("{}-{} 添加了 {}", "DynamicDataSourceAspect", "setDataSource", dataSourceKey);
        try {
            return joinPoint.proceed();
        } finally {
            logger.info("{}-{} 移除了 {}", "DynamicDataSourceAspect", "setDataSource", dataSourceKey);
            MultipleDataSource.clearLookupKey();
        }
    }
}